package com.yunshipei.ui.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;

import com.yunshipei.base.BaseActivity;
import com.yunshipei.base.EnterBaseSubscriber;
import com.yunshipei.common.Globals;
import com.yunshipei.common.net.HttpMethods;
import com.yunshipei.common.wedigt.YspTitleBar;
import com.yunshipei.enterplorer.R;
import com.yunshipei.manager.YspPreferences;
import com.yunshipei.model.YspEvent;
import com.yunshipei.ui.fragment.YspConversationListFragment;

import org.json.JSONObject;

import butterknife.Bind;
import butterknife.ButterKnife;
import io.rong.app.RongCloudEvent;
import io.rong.eventbus.EventBus;
import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imkit.fragment.ConversationListFragment;
import io.rong.imkit.model.Event;
import io.rong.imlib.RongIMClient;

public class StandEditionMessageActivity extends BaseActivity {

    @Bind(R.id.et_title_bar)
    protected YspTitleBar mTitleBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stand_edition);
        ButterKnife.bind(this);
        mTitleBar.setTitle("消息");
        String token = getIntent().getStringExtra("token");
        String uuid = getIntent().getStringExtra("uuid");
        rongIMConnect(token, uuid);
    }

    private int tokenIncorrectCount = 0;

    private void rongIMConnect(String token, final String uuid) {
        RongIM.connect(token, new RongIMClient.ConnectCallback() {

            @Override
            public void onTokenIncorrect() {
                if (tokenIncorrectCount < 3) {
                    //刷新Token
                    HttpMethods.getInstance().reFetchToken(uuid, new EnterBaseSubscriber() {
                        @Override
                        public void onSuccess(JSONObject data) {
                            String newToken = data.optString("token");
                            if (!TextUtils.isEmpty(newToken)) {
                                YspPreferences.getInstance().getSharedPreferences().edit().putString(Globals.YSP_TOKEN, newToken).apply();
                                rongIMConnect(newToken, uuid);
                            } else {
                                onFailure("token为空");
                            }
                        }

                        @Override
                        public void onFailure(String errorMessage) {
                        }
                    });
                    tokenIncorrectCount++;
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode arg0) {
                attachConversationFragment();
            }

            @Override
            public void onSuccess(String arg0) {
                YspPreferences.getInstance().getSharedPreferences().edit().putBoolean("RCSconnectStatus", true).apply();
                RongCloudEvent.getInstance().setOtherListener();
                EventBus.getDefault().post(new YspEvent.ConnectEvent());
                RongContext.getInstance().getEventBus().post(Event.ConnectEvent.obtain(true));
                attachConversationFragment();
            }
        });
    }

    private void attachConversationFragment() {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        Fragment fragment = fragmentManager.findFragmentById(R.id.fl_conversion_content);
        ConversationListFragment conversationListFragment;
        if (fragment != null) {
            conversationListFragment = (ConversationListFragment) fragment;
            transaction.show(conversationListFragment).commitAllowingStateLoss();
        } else {
            conversationListFragment = YspConversationListFragment.newInstance(this);
            transaction.replace(R.id.fl_conversion_content, conversationListFragment, ConversationListFragment.class.getName()).commitAllowingStateLoss();
        }
    }
}
